#!/usr/bin/env python
#coding=utf-8
from django import newforms as forms
from django.http import HttpResponse
from datetime import datetime
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate
from django.contrib.auth import login as do_login
from django.contrib.auth import logout as do_logout
from blogpy.blog.models import Post
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from blogpy.blog.js import *

def login(request):
    if request.method == 'POST':
        if request.POST and request.POST.has_key('username') and request.POST.has_key('password'):
            user = authenticate(username=request.POST['username'],password=request.POST['password'])
            if user:
                if user.is_active:
                    do_login(request, user)
                    user.last_login = datetime.now()
                    user.save()
                return HttpResponse(jsSucc('登陆成功'))
        return HttpResponse(jsFail('输入登录信息有误'))
    if request.method == 'GET':
        return render_to_response('blog_templates/home/login.html',{})

def logout(request):
    do_logout(request)
    return HttpResponse(jsSucc('退出成功'))

@login_required
def addBlog(request):
    EntryForm = forms.models.form_for_model(Post)
    EntryForm.base_fields['content'].widget = forms.Textarea(attrs={'rows': 10, 'cols': 50})
    if request.method == 'POST':
        form = EntryForm(request.POST)
        if form.is_valid():
            entry = form.save(commit=False)
            try:
                entry.save()
            except:
                return HttpResponse(jsSucc('添加失败'))
            else:
                return HttpResponse(jsSucc('添加成功'))
    if request.method == 'GET':
        form = EntryForm()
    addcatalog ='''</select>
    <a onclick="return showAddAnotherPopup(this);" id="add_id_catalog" class="add-another" href="/admin/blog/category/add/">
     <img width="10" height="10" alt="Add Another" src="/media/img/admin/icon_addlink.gif"/>
    </a>
    '''
    form = str.replace(form.as_ul().encode('utf8'),'id="id_pubdate"','id="id_pubdate" class="vDateField required"')
    form = str.replace(form,'</select>',addcatalog)
    payload = {'form':form}
    return render_to_response('blog_templates/home/addblog.html',payload)

@login_required
def editBlog(request, post_id):
    blog_post = get_object_or_404(Post, id=post_id)
    EntryForm = forms.models.form_for_instance(blog_post)
    EntryForm.base_fields['content'].widget = forms.Textarea(attrs={'rows': 10, 'cols': 50})
    if request.method == 'POST':
        form = EntryForm(request.POST)
        if form.is_valid():
            entry = form.save(commit=False)
            try:
                entry.save()
            except:
                return HttpResponse(jsSucc('编辑失败'))
            else:
                return HttpResponse(jsSucc('编辑成功'))
    if request.method == 'GET':
        form = EntryForm()
    addcatalog ='''</select>
    <a onclick="return showAddAnotherPopup(this);" id="add_id_catalog" class="add-another" href="/admin/blog/category/add/">
     <img width="10" height="10" alt="Add Another" src="/media/img/admin/icon_addlink.gif"/>
    </a>
    '''
    form = str.replace(form.as_ul().encode('utf8'),'id="id_pubdate"','id="id_pubdate" class="vDateField required"')
    form = str.replace(form,'</select>',addcatalog)
    payload = {'form':form}
    return render_to_response('addblog.html',payload)

@login_required
def delBlog(request, post_id):
    blog_post = get_object_or_404(Post, id=post_id)
    try:
        blog_post.delete()
    except:
        return HttpResponse(jsFail('删除失败'))
    else:
        return HttpResponse(jsSucc('删除成功'))